package org.example.util;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Optional;

/**
 * Base64串编解码工具.
 *
 * @author KazuHo
 * @version 1.0
 * @since 2021-08-16
 */
public final class Base64Util {
    /**
     * 解码base64串.
     *
     * @param base64 base64串
     * @return 解码后的base64串
     */
    public static String decode(String base64) {
        byte[] bytes =
                Optional.ofNullable(base64)
                        .map(String::trim)
                        .map(bt -> bt.getBytes(StandardCharsets.UTF_8))
                        .orElseThrow(() -> new RuntimeException("invalid base64 string."));

        return new String(Base64.getDecoder().decode(bytes), StandardCharsets.UTF_8);
    }

    /**
     * 编码字符串.
     *
     * @param plain 字符串明文
     * @return base64串
     */
    public static String encode(String plain) {
        byte[] bytes =
                Optional.ofNullable(plain)
                        .map(String::trim)
                        .map(p -> p.getBytes(StandardCharsets.UTF_8))
                        .orElseThrow(() -> new RuntimeException("invalid plain string."));

        return Base64.getEncoder().encodeToString(bytes);
    }
}
